package com.echo.im.engin.netty.handler;

import com.echo.im.engin.packet.Packet;
import com.echo.im.engin.netty.packet.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

import java.util.List;

/**
 * @author: echo
 * @time: 2024-08-23
 */
public class PacketCodecHandler extends MessageToMessageCodec<WebSocketFrame, Packet> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Packet packet, List<Object> list) throws Exception {
        ByteBuf buf = PacketCodeC.INSTANCE.encode(ByteBufAllocator.DEFAULT.buffer(), packet);
        list.add(new BinaryWebSocketFrame(buf));
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, WebSocketFrame webSocketFrame, List<Object> list) throws Exception {
        list.add(PacketCodeC.INSTANCE.decode(webSocketFrame.content()));
    }
}
